package com.tolerate.managespringboot.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.http.server.HttpServerResponse;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tolerate.managespringboot.Utils.SftpUtils;
import com.tolerate.managespringboot.Utils.TokenUtils;
import com.tolerate.managespringboot.common.Result;
import com.tolerate.managespringboot.entity.User;
import com.tolerate.managespringboot.mapper.UserMapper;
import com.tolerate.managespringboot.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SftpUtils sftpUtils;


    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        return userService.login(user);
    }

    @PostMapping
    public boolean saveOrUpdateById(@RequestBody User user) {
        return userService.saveUser(user);
    }

    @PostMapping("/register")
    public Result getById(@RequestBody User user) {
        // 重要服务，前后端都需要校验
        String username = user.getUsername();
        String password = user.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error("账号密码不能为空");
        }
        if (userService.getOne(new QueryWrapper<User>().eq("username", username)) != null) {
            return Result.error("账号已存在");
        }
        boolean save = userService.save(user);
        if (save) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    @DeleteMapping("/{id}")
    public Integer deleteById(@PathVariable Integer id) {
        return userMapper.deleteById(id);
    }

    @PostMapping("del/batch")
    public Integer deleteBatch(@RequestBody List<Integer> ids) {
        return userMapper.deleteBatchIds(ids);
    }

    @GetMapping("/page")
    public Map page(Integer pageNum, Integer pageSize, String username, String email, String address) {
        IPage<User> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 使用条件构造查询，避免当参数为空时执行不必要的like操作
        if (username != null && !username.trim().isEmpty()) {
            lambdaQueryWrapper.like(User::getUsername, username.trim());
        }
        if (email != null && !email.trim().isEmpty()) {
            lambdaQueryWrapper.like(User::getEmail, email.trim());
        }
        if (address != null && !address.trim().isEmpty()) {
            lambdaQueryWrapper.like(User::getAddress, address.trim());
        }
        lambdaQueryWrapper.orderByDesc(User::getCreateTime);
        IPage<User> userPage = userMapper.selectPage(page, lambdaQueryWrapper);


        // 返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("data", userPage.getRecords());
        map.put("total", userPage.getTotal());
        return map;
    }

    /**
     * 导出
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws Exception {
// 获取数据所有数据
        List<User> userList = userMapper.selectList(null);
        // 导出
        // 指定导入的文件路径
        // ExcelWriter writer = ExcelUtil.getWriter("E:\\test.xlsx");
        // true：表示不指定路径，在内存操作，直接写在浏览器中
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义表头，不指定，就是实体的字段
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("phone", "手机号");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("createTime", "创建时间");

        // 写入数据,使用默认样式，强制输出标题
        writer.write(userList, true);

        // 设置响应到浏览器的格式
        // 获取设置文件名
        String finalFileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + finalFileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    @PostMapping("/importExcel")
    public void importExcel(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        ExcelReader excelReader = ExcelUtil.getReader(inputStream);

        List<User> userList = new ArrayList<>();
        // 获取所有sheet页的名称
        List<String> sheetNames = excelReader.getSheetNames();
        for (String sheetName : sheetNames) {
            List<List<Object>> read = excelReader.setSheet(sheetName).read(1);
            read.forEach(list -> {
                User user = new User();
                user.setUsername(list.get(0).toString());
                user.setPassword(list.get(1).toString());
                user.setNickname(list.get(2).toString());
                user.setPhone(list.get(3).toString());
                userList.add(user);
            });
        }
        // 保存数据
        userService.saveBatch(userList);
    }


    @PostMapping("/info")
    public Result getInfo(@RequestBody User user) throws Exception {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, user.getUsername());
        List<User> list = userService.list(lambdaQueryWrapper);
        return Result.success(list.get(0));
    }

}
